# 准确率、错分样例图
from tensorflow import keras
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
import numpy as np
from mobilenet import MobileNet

# 设置图片的高、宽
im_height = 224
im_width = 224

# 设置训练的样本数
batch_size = 64

# 测试集路径
validation_dir = "./myData/test"

# 定义测试集图像生成器，并对图像进行预处理
validation_image_generator = ImageDataGenerator(rescale=1./255) # 归一化

# 使用图像生成器从测试集validation_dir中读取样本
val_data_gen = validation_image_generator.flow_from_directory(directory=validation_dir,  # 从测试集路径读取图片
                                                              batch_size=batch_size,  # 一次训练所选取的样本数
                                                              shuffle=False,  # 不打乱标签
                                                              target_size=(im_height, im_width),  # 图片resize到224x224大小
                                                              class_mode='categorical')  # one-hot编码

# 测试集样本数 :5000
total_val = val_data_gen.n
labels = ['cats', 'dogs']
model = MobileNet(input_shape=(224, 224, 3),classes=2,alpha=0.25)
model.load_weights('./mySave/model.h5')

# 预测测试集数据整体准确率,显示进度条
y_pred = model.predict(val_data_gen, total_val // batch_size + 1,verbose=1)
y_test = val_data_gen.classes
y_test = np.reshape(y_test, (-1, 1))

# 计算准确率
print("准确率：", keras.metrics.SparseCategoricalAccuracy()(y_test, y_pred))

# 转换为预测标签
y_pred_classes = np.argmax(y_pred, axis=1)

# 绘制错分样例图
count = 10
y_pred = np.reshape(y_pred_classes, (-1, 1))
ins = y_test != y_pred
diff_index = np.where(ins == True)[0]
print('错误分类的图下标：',diff_index) # 大约137个
plt.figure()
it = iter(val_data_gen)
x_test,_ = next(val_data_gen)
mmm = 1
for x in it:
    if mmm > 6:
        break
    yy,_ = x
    x_test = np.concatenate((x_test,yy),axis=0)
    mmm = mmm +1
for i in range(count):
    j = diff_index[i]
    img = x_test[j]      # 设值28*28
    plt.subplot(2, 5, i+1, xticks=[], yticks=[])# 2*5子图显示
    plt.imshow(img)
    ii = y_test[j][0]
    jj = y_pred[j][0]
    plt.title(f'{labels[ii]}--> {labels[jj]}', fontproperties='SimHei')  # 显示标题
    plt.subplots_adjust(wspace=0.1, hspace=0.2)# 调整子图间距
plt.show()
